<template>
  <edit-card :title="title" :type="taskId ? 'edit' : 'add'" :loading="loading" @confirm="submitForm">
    <div class="edit-task">
      <a-form
        ref="taskFormRef"
        :model="formState"
        :rules="taskRules"
        :label-col="{ style: { width: '120px' } }"
        class="w-560"
        label-align="left"
      >
        <a-form-item label="任务名称" name="name">
          <div class="w-440">
            <a-input v-model:value="formState.name" v-trim placeholder="请输入任务名称" :disabled="!!taskId" :maxlength="200" />
          </div>
        </a-form-item>
        <a-form-item label="描述" name="description">
          <div class="w-440">
            <a-textarea v-model:value="formState.description" v-trim placeholder="请输入描述" :rows="5" :maxlength="200" show-count />
          </div>
        </a-form-item>
        <a-form-item label="数据类型" name="markType">
          <div class="w-704">
            <select-dmp-type v-model:task-type="formState.markType" v-model:sub-task-type="formState.markSubType" />
          </div>
        </a-form-item>
        <a-form-item label="数据集" name="dataIds">
          <div class="w-866">
            <g-select-tree-data
              ref="selectDataBucketRef"
              v-model:checkedIds="formState.dataIds"
              type-name="数据集"
              :disabled="!!taskId"
              :has-modal="false"
              :get-tree-data-api="selectTreeDataApi.dataBucketTree"
              :get-collect-tree-data-api="selectTreeDataApi.collectDataBucketTree"
              :get-list-data-api="selectTreeDataApi.searchBucketList"
              :get-collect-list-data-api="selectTreeDataApi.collectSearchBucketList"
              :field-names="{ children: 'children', title: 'name', key: 'id' }"
            >
              <template #selected-tools>
                <a-tooltip title="仅从已选数据集中抽取满足“数据处理规则”格式条件的文件">
                  <i class="iconfont icon-information-fill text-color-4 ml-8 h-22"></i>
                </a-tooltip>
              </template>
            </g-select-tree-data>
          </div>
        </a-form-item>
        <a-form-item label="数据处理规则" name="taskRule">
          <div class="w-704">
            <a-form-item-rest>
              <mark-rule ref="markRuleRef" v-model:taskRule="formState.taskRule" :sub-task-type="formState.markSubType" />
            </a-form-item-rest>
          </div>
        </a-form-item>
        <a-form-item>
          <template #label>
            <span>标签组</span>
            <a-tooltip title="文本、音频、表格类标注任务默认不使用“标签属性”">
              <i class="iconfont icon-information-fill text-color-4 ml-8"></i>
            </a-tooltip>
          </template>
          <div class="w-704">
            <a-form-item-rest>
              <select-tag-group
                ref="selectTagGroupRef"
                v-model:tag-group-id="formState.baseTagGroupId"
                :sub-task-type="formState.markSubType"
              />
            </a-form-item-rest>
          </div>
        </a-form-item>
      </a-form>
    </div>
  </edit-card>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { cloneDeep } from 'g6-fn'
  import { computed, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute } from 'vue-router'

  import GSelectTreeData from '@/components/GSelectTreeData/index.vue'
  import router from '@/router'
  import { dmpTaskApi, selectTreeDataApi } from '@/services/api'
  import { validateBitLen, validateDirName } from '@/utils'

  import { DmpSubTaskType, DmpTaskType } from '../types/taskType'
  import MarkRule from './components/MarkRule/index.vue'
  import SelectDmpType from './components/SelectDmpType.vue'
  import SelectTagGroup from './components/SelectTagGroup.vue'

  interface FromState {
    dataIds: string[]
    description?: string
    name: string
    markType: DmpTaskType
    markSubType: DmpSubTaskType
    taskRule: any
    baseTagGroupId?: string
  }

  const route = useRoute()

  const taskId = route.params.id as string | ''
  const title = computed(() => (taskId ? `编辑任务（${formState.value.name}）` : '创建任务'))

  const taskFormRef = ref()
  const formState = ref<FromState>({
    name: '',
    description: '',
    markType: DmpTaskType.img,
    markSubType: DmpSubTaskType.imgClass,
    taskRule: {},
    dataIds: [],
    baseTagGroupId: undefined
  })

  let validateDataBucket = async (rule: Rule, value: string) => {
    if (value.length === 0) {
      return Promise.reject('请选择数据集')
    }
    return Promise.resolve()
  }

  const taskRules: Record<string, Rule[]> = {
    name: [
      { required: true, trigger: 'change', message: '请输入任务名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ],
    dataIds: [{ required: true, trigger: 'change', validator: validateDataBucket }],
    taskRule: [{ required: true, trigger: 'change' }],
    markType: [{ required: true, trigger: 'change', message: '请选择方式' }]
  }

  // 数据集数据选择组件爱你
  const selectDataBucketRef = ref<InstanceType<typeof GSelectTreeData>>()
  // 数据处理规则组件
  const markRuleRef = ref<InstanceType<typeof MarkRule>>()
  // 标签组选择组件
  const selectTagGroupRef = ref<InstanceType<typeof SelectTagGroup>>()

  const { loading, runAsync } = useRequest(taskId ? dmpTaskApi.edit : dmpTaskApi.add)

  const submitForm = async () => {
    await taskFormRef.value.validate()

    const params: Record<string, any> = formState.value
    params.tagIds = cloneDeep(selectTagGroupRef.value?.selectedKeys)
    if (taskId) {
      params.id = taskId
    }
    await runAsync({ ...params }, { isAddUid: true })
    message.success('操作成功')
    router.back()
  }
</script>

<style lang="less" scoped>
  .edit-task {
    :deep(.ant-form-item) {
      margin-bottom: 40px;
    }

    :deep(.ant-form-item-label > label::after) {
      display: none;
    }

    :deep(.ant-radio-wrapper) {
      margin-right: 24px;
    }

    .ant-radio-wrapper :deep(.ant-transfer-list) {
      position: relative;

      .ant-transfer-list-header {
        height: 39px;
        background: #fafafa;
      }

      &:first-child {
        .ant-transfer-list-header {
          &::after {
            content: '待选';
            position: absolute;
            right: 8px;
          }
        }
      }

      &:last-child {
        .ant-transfer-list-header {
          &::after {
            content: '已选';
            position: absolute;
            right: 8px;
          }
        }
      }

      .ant-input-affix-wrapper {
        height: 32px;
        min-height: 32px !important;
      }
    }

    .tag-select {
      display: flex;

      .left {
        margin-right: 80px;
      }
    }
  }
</style>
